import React from 'react';
import _ from 'lodash';
import { Link } from 'react-router';
import { connect } from 'react-redux';
import classNames from 'classnames';
import {
  API_URL,
  formItemLayout,
  PORTRAIT,
  _validate,
  check_rules,
  available,
  checkExists,
  fetchDatum,
  portraitSet,
  fetchAttachByEntry,
  fetchAttachById,
  special_operate,
  updateUser,
  getUser,
  putPW,
  fetchPortrait
} from '../../store/actions';
import {message, Radio, Checkbox, Button, Select, Input, Form, Icon, Switch, Table, Upload, Alert,Tag,Row,Col,Tabs} from 'antd';

function noop() {
    return false;
}
const TabPane = Tabs.TabPane,
  CheckboxGroup = Checkbox.Group,
  FormItem = Form.Item,
  Option = Select.Option,
  RadioGroup = Radio.Group,
  RadioButton = Radio.Button;
class BaseInfo extends React.Component{
    constructor(props){
        super(props);
        this.state = {
            data: null,
            portrait: this.props.portrait,
            fileList:{},
            user: this.props.user
        }
    }
    setFieldsValue(){
        const user = this.state.user.user,
          initData = {
              name:user.name,
              nickname:user.nickname,
              gender:user.gender,
              mail:user.mail,
              mobile:user.mobile,
              idcard:user.idcard
          },
          initForm = this.props.form.setFieldsValue;
        initForm(initData)
    }
    componentWillMount(){
        this.setFieldsValue()
    }
    componentWillReceiveProps(nextProp){
        this.setState({
            data:nextProp.data,
            portrait:nextProp.portrait,
            user:nextProp.user
        })
    }
    normFile(e) {
        if (Array.isArray(e)) {
            return e;
        }
        return e && e.fileList;
    }
    portraitHandler(info){
        const _this = this;
        return portraitSet(info,_this)
    }
    fileTypeLimit(types,file){
        const fileType = file.type,
          typeStr = types.join('、');
        let isOk = false;
        for(let i = 0;i<types.length;i++){
            try{
                isOk = new RegExp(types[i]).test(fileType);
                if(isOk){
                    break;
                }
            }catch(e){consloe.log(e)}
        }
        if(!isOk){
            message.error(`您上传文件的格式只能是：${typeStr}格式`);
            return isOk
        }
    }
    checkName(rule, value, callback) {
        this.props.checkForm('account', 'name', rule, value, callback)
    }
    checkNickname(rule, value, callback) {
        this.props.checkForm('account', 'nickname', rule, value, callback)
    }
    checkMail(rule, value, callback) {
        this.props.checkForm('common', 'mail', rule, value, callback)
    }
    checkMobile(rule, value, callback) {
        this.props.checkForm('common', 'mobile', rule, value, callback)
    }
    checkIdcard(rule, value, callback) {
        this.props.checkForm('common', 'idcard', rule, value, callback)
    }
    handleSubmit(e){
        e.preventDefault();
        const _this = this;
        _validate(e, _this, function (data) {
            let _data = Object.assign({}, data);
            let attachment = [],
              willUploadFiles = _this.state.fileList;
            _.forIn(willUploadFiles,(v,k)=>{
                if(v.length> 0 ){
                    attachment.push({[k]:v})
                }
            });
            _data.attachment = attachment;
            _data.user_id = _this.state.user.user.user_id;
            _data.account_id = _this.state.user.user.account_id;
            _this.props.dispatch(updateUser(_data, function () {
                message.success('信息更新成功', 3);
                _this.props.updateUser(_data)
            }))
        })
    }
    render(){
        if(!this.state.data){
            return (<div>加载中</div>)
        }
        const _gender = this.state.data.gender && this.state.data.gender.map(_g => {
                return (<RadioButton key={_g.id} value={_g.code}>{_g.name}</RadioButton>)
            }),
          {getFieldProps} = this.props.form;

        const nameProps = getFieldProps('name', {
            rules: [
                {required: true, message: '请输入真实姓名'},
                {validator: this.checkName.bind(this)}
            ]
        });
        const nicknameProps = getFieldProps('nickname', {
            rules: [
                {required: false},
                {validator: this.checkNickname.bind(this)}
            ]
        });
        const idCardProps = getFieldProps('idcard', {
            rules: [
                {required: true,message:'请输入身份证号'},
                {validator: this.checkIdcard.bind(this)}
            ]
        });
        const emailProps = getFieldProps('mail', {
            rules: [
                {required: false},
                {validator: this.checkMail.bind(this)}
            ]
        });
        const mobileProps = getFieldProps('mobile', {
            rules: [
                {required: true,message:'请输入手机号'},
                {validator: this.checkMobile.bind(this)}
            ]
        });
        const genderProps = getFieldProps('gender', {
            rules: [
                {required: true, message: '请选择专家性别'}
            ]
        });
        //TODO attachment portrait 暂时不用
        /*const portraitProps = getFieldProps('portrait', {
            normalize: this.normFile.bind(this),
            onChange: this.portraitHandler.bind(this)
        });
        let curPortrait = null;
        if(this.state.fileList && this.state.fileList.portrait){
            curPortrait = {};
            const _id = this.state.fileList.portrait;
            curPortrait.id = _id;
            curPortrait.url = `${API_URL}attachment/${_id}?accessToken=${this.state.user.accessToken}`
        }else{
            curPortrait = this.state.portrait
        }*/
        return (
          <Form horizontal form={this.props.form}>
              {/* TODO attachment portrait 暂时不用
              <FormItem
                {...formItemLayout}
                label="头像"
              >
                  <Upload
                    name="files"
                    showUploadList={false}
                    action={`${API_URL}upload/portrait?accessToken=${this.props.user.accessToken}`}
                    beforeUpload = {this.fileTypeLimit.bind(this,['jpg','gif','png','jpeg'])}
                    help="只能上传图片格式的文件"
                    {...portraitProps}
                  >
                      <div
                        style={{
                            width: '100px',
                            overflow: 'hidden',
                            backgroundColor: '#ddd',
                            textAlign: 'center'
                        }}>
                          {curPortrait?<img style={{
                            display: 'block',
                            width: '100%'
                        }} src={curPortrait.url} />:'没有上传头像'}
                      </div>
                      <Button type="ghost">
                          <Icon type="upload" /> 选择并上传头像
                      </Button>
                  </Upload>
              </FormItem>*/}
              <FormItem
                {...formItemLayout}
                label="姓名"
              >
                  <Input
                    {...nameProps}
                    placeholder="请输入真实姓名"
                  />
              </FormItem>
              <FormItem
                {...formItemLayout}
                label="昵称"
              >
                  <Input
                    {...nicknameProps}
                    placeholder="请输入昵称"
                  />
              </FormItem>
              <FormItem
                {...formItemLayout}
                label="性别"
              >
                  <RadioGroup {...genderProps}>
                      {_gender}
                  </RadioGroup>
              </FormItem>
              <FormItem
                {...formItemLayout}
                label="身份证号"
              >
                  <Input {...idCardProps} placeholder="请输入身份证号"/>
              </FormItem>
              <FormItem
                {...formItemLayout}
                label="Email"
              >
                  <Input {...emailProps} placeholder="请输入电子邮件地址"/>
              </FormItem>
              <FormItem
                {...formItemLayout}
                label="手机号"
              >
                  <Input {...mobileProps} placeholder="请输入手机号"/>
              </FormItem>
              <FormItem wrapperCol={formItemLayout.noLabel}>
                  <Button type="primary" onClick={this.handleSubmit.bind(this)}>保存</Button>
                  &nbsp;&nbsp;&nbsp;&nbsp;
                  <Button onClick={this.setFieldsValue.bind(this)}>重置</Button>
              </FormItem>
          </Form>
        )
    }
}
BaseInfo = Form.create()(BaseInfo);


class __pane2 extends React.Component{
    constructor(props){
        super(props);
        this.state = {
            user: this.props.user,
            fileList:{}
        };
        this.handleChange = this.handleChange.bind(this);
        this.normFile = this.normFile.bind(this)
    }
    normFile(e){
        if (Array.isArray(e)) {
            return e;
        }
        return e && e.fileList;
    }
    handleChange(info){
        //if (info.file.status !== 'uploading') {}
        if (info.file.status === 'done') {
            message.success(`${info.file.name} 上传成功。`);
            this.props.dispatch(fetchPortrait(this.props.user.user.account_id))
        } else if (info.file.status === 'error') {
            message.error(`${info.file.name} 上传失败。`);
        }
    }
    componentWillMount(){
        this.props.dispatch(fetchPortrait(this.props.user.user.account_id))
    }
    componentWillReceiveProps(nextProp){
        this.setState({
            portrait:nextProp.portrait.url
        })
    }
    render(){
        const { getFieldProps } = this.props.form;
        const upload1 = getFieldProps('upload', {
            valuePropName: 'portrait',
            normalize: this.normFile,
            onChange: this.handleChange
        });
        return (
          <div>
              <Form horizontal onSubmit={this.handleSubmit}>
                  <FormItem
                    label="上传头像"
                    labelCol={{ span: 6 }}
                    wrapperCol={{ span: 18 }}
                    help="请上传头像图片"
                  >
                      <Upload
                        name="portrait"
                        showUploadList={false}
                        action= {`${API_URL}${PORTRAIT}?accessToken=${this.props.user.accessToken}`}
                        {...upload1}
                      >
                          <div style={{
                                width: '100px',
                                overflow: 'hidden',
                                backgroundColor: '#ddd'
                            }}><img style={{
                                display: 'block',
                                width: '100%'
                            }} src={this.state.portrait} /></div>
                          <Button type="ghost">
                              <Icon type="upload" /> 选择并上传头像
                          </Button>
                      </Upload>
                  </FormItem>
              </Form>
          </div>
        )
    }

}
let _pane2 = Form.create()(__pane2);
_pane2 = connect((state)=>{
    const {portrait} = state.rootReducer;
    return {portrait}
})(_pane2)



class ResetPW extends  React.Component{
    constructor(props){
        super(props);
        this.state = {
            passBarShow: false, // 是否显示密码强度提示条
            rePassBarShow: false,
            passStrength: 'L', // 密码强度
            rePassStrength: 'L',
            user:this.props.user
        };
        this.checkPass = this.checkPass.bind(this);
        this.checkPass2 = this.checkPass2.bind(this);
        this.resetFields = this.resetFields.bind(this)

    }
    getPassStrength(value, type) {
        if (value) {
            let strength;
            // 密码强度的校验规则自定义，这里只是做个简单的示例
            if (value.length < 6) {
                strength = 'L';
            } else if (value.length <= 9) {
                strength = 'M';
            } else {
                strength = 'H';
            }
            if (type === 'password') {
                this.setState({ passBarShow: true, passStrength: strength });
            } else {
                this.setState({ rePassBarShow: true, rePassStrength: strength });
            }
        } else {
            if (type === 'pass') {
                this.setState({ passBarShow: false });
            } else {
                this.setState({ rePassBarShow: false });
            }
        }
    }
    checkPassword(rule, value, callback) {
        this.props.checkForm('account', 'password', rule, value, callback)
    }
    checkPass(rule, value, callback) {
        const form = this.props.form;
        this.getPassStrength(value, 'password');
        if (form.getFieldValue('password')) {
            form.validateFields(['rePass'], { force: true });
        }
        callback();
    }

    checkPass2(rule, value, callback) {
        const form = this.props.form;
        this.getPassStrength(value, 'rePass');
        if (value && value !== form.getFieldValue('password')) {
            callback('两次输入密码不一致！');
        } else {
            callback();
        }
    }
    renderPassStrengthBar(type) {
        const strength = type === 'password' ? this.state.passStrength : this.state.rePassStrength;
        const classSet = classNames({
            'ant-pwd-strength': true,
            'ant-pwd-strength-low': strength === 'L',
            'ant-pwd-strength-medium': strength === 'M',
            'ant-pwd-strength-high': strength === 'H'
        });
        const level = {
            L: '低',
            M: '中',
            H: '高'
        };
        return (
          <div style={{
            position:'absolute',
            right:'0',
            top:'0'
          }}>
              <ul className={classSet}>
                  <li className="ant-pwd-strength-item ant-pwd-strength-item-1"> </li>
                  <li className="ant-pwd-strength-item ant-pwd-strength-item-2"> </li>
                  <li className="ant-pwd-strength-item ant-pwd-strength-item-3"> </li>
                    <span className="ant-form-text">
                        {level[strength]}
                    </span>
              </ul>
          </div>
        );
    }
    handleSubmit(e) {
        const _this = this;
        _validate(e,_this,function(values){
            const sendData = {
                old:values.oldPW,
                changeto:values.rePass
            };
            _this.props.dispatch(putPW(sendData,function(){
                message.success('修改密码成功，请牢记新密码',1);
                _this.resetFields()
            },function(res){
                message.error(res.head.msg,1);
                _this.resetFields()
            }))
        });
    }
    resetFields(){
        this.setState({
            passBarShow: false, // 是否显示密码强度提示条
            rePassBarShow: false
        },function(){
            this.props.form.resetFields()
        })
    }
    render(){
        const { getFieldProps } = this.props.form;
        const oldPassProps = getFieldProps('oldPW', {
            rules: [
                { required: true, whitespace: true,message: '请输入原始密码' }
            ]
        });
        const passProps = getFieldProps('password', {
            rules: [
                { required: true, min:6,max:20,whitespace: true,message: '必填项' },
                { validator: this.checkPass },
                { validator: this.checkPassword.bind(this) }
            ]
        });
        const rePassProps = getFieldProps('rePass', {
            rules: [{
                required: true,
                whitespace: true,
                message: '请再次输入密码'
            }, {
                validator: this.checkPass2
            }]
        });
        return (
          <div>
              <Form horizontal form={this.props.form}>

                  <FormItem
                    {...formItemLayout}
                    label="原始密码"
                  >
                      <Input {...oldPassProps}
                        type="password"
                        onContextMenu={noop} onPaste={noop} onCopy={noop} onCut={noop}
                        autoComplete="off"
                        id="oldPW"
                      />
                  </FormItem>
                  <FormItem wrapperCol={formItemLayout.noLabel}>
                      设置新的密码
                  </FormItem>
                  <FormItem
                    {...formItemLayout}
                    label="新密码"
                  >
                      <Input
                        {...passProps}
                        type="password"
                        onContextMenu={noop}
                        onPaste={noop}
                        onCopy={noop}
                        onCut={noop}
                        autoComplete="off"
                        id="password"
                        style={{
                            position:'relative',
                            paddingRight:'100px'
                        }}
                      />
                      {this.state.passBarShow ? this.renderPassStrengthBar('password') : null}
                  </FormItem>
                  <FormItem
                    {...formItemLayout}
                    label="确认新密码"
                  >
                      <Input
                        {...rePassProps}
                        type="password"
                        onContextMenu={noop}
                        onPaste={noop}
                        onCopy={noop}
                        onCut={noop}
                        autoComplete="off"
                        id="rePass"
                      />
                  </FormItem>
                  <FormItem wrapperCol={formItemLayout.noLabel}>
                      <Button type="primary" onClick={this.handleSubmit.bind(this)}>修改密码</Button>
                      &nbsp;&nbsp;&nbsp;&nbsp;
                      <Button onClick={this.resetFields.bind(this)}>重置</Button>
                  </FormItem>
              </Form>

          </div>
        )
    }
}
ResetPW = Form.create()(ResetPW);
class User extends React.Component{
    constructor(props){
        super(props);
        this.state={
            user:this.props.user
        }
    }
    componentWillMount(){
        const _this = this;
        _this.props.dispatch(fetchDatum([
            {
                name: 'gender',
                enabled: true
            }
        ], function (datas) {
            _this.props.dispatch(check_rules(function (rules) {
                _this.setState({
                    rules: rules.content,
                    data: datas
                })
            }));
        }));
        /*const attachment_type = {id:_this.state.user.user.user_id,type:'portrait'};
        _this.props.dispatch(fetchAttachByEntry(attachment_type,function (portrait) {
            let last = {};
            if(portrait.content.length> 1){
                _.forEach(portrait.content,(o,i)=>{
                    if((i+1)<portrait.content.length){
                        _this.props.dispatch(fetchAttachById(o.id,0));
                    }else{
                        last = o
                    }
                })
            }else{
                last = portrait.content[0]
            }
            _this.setState({
                portrait: {
                    id:last.id,
                    url:`${API_URL}attachment/${last.id}?accessToken=${_this.state.user.accessToken}`
                }
            })
        }));*/
    }
    componentDidMount(){}
    updateUserData(newData){
        if(window.sessionStorage){
            const sessionUser = JSON.parse(window.sessionStorage.getItem('user'));
            if(sessionUser){
                delete newData.attachment;
                let newUser = Object.assign({},sessionUser.user,newData);
                newUser = Object.assign({},sessionUser,{user:newUser});
                const str = JSON.stringify(newUser);
                window.sessionStorage.setItem('user',str);
                //this.props.dispatch(getUser({content:newUser}));
            }
        }
    }
    checkForm(a, b, rule, value, callback) {
        const _r = eval(this.state.rules[a][b]['expr']),
          msg = this.state.rules[a][b]['rule'];
        (function () {
            const result = _r.test(value);
            if (!result && value) {
                callback(msg)
            } else {
                callback();
            }
        })()
    }
    componentWillReceiveProps(nextProp){
        this.setState({
            user:nextProp.user
        })
    }
    render(){
        return (
          <Tabs
            size="default"
          >
              <TabPane tab="基础信息" key="1">
                  <BaseInfo
                    user={this.state.user}
                    data={this.state.data}
                    checkForm={this.checkForm.bind(this)}
                    dispatch={this.props.dispatch}
                    portrait={this.state.portrait}
                    updateUser={this.updateUserData.bind(this)}
                  />
              </TabPane>
              <TabPane tab="设置头像" key="2">
                  <_pane2 user={this.props.user} dispatch={this.props.dispatch} />
              </TabPane>
              <TabPane tab="修改密码" key="3">
                  <ResetPW
                    user={this.state.user}
                    checkForm={this.checkForm.bind(this)}
                    dispatch={this.props.dispatch}
                  />
              </TabPane>

          </Tabs>
        )
    }
}
export default User = connect((state)=>{
    const {user} = state.rootReducer;
    return {user}
})(User)
